<?php

namespace PhpBoot\Utils;

use Zipkin\Endpoint;
use Zipkin\Propagation\Map;
use Zipkin\Reporters\Http;
use Zipkin\Samplers\BinarySampler;
use Zipkin\TracingBuilder;

class ZipkinHelper
{
    public static $enabled;
    public static $tracing;
    public static $tracer;
    public static $rootSpan;

    public static function init($appName, $endpointUrl, $enabled)
    {
        self::$enabled = $enabled;
        if (self::$enabled) {
            $endpoint = Endpoint::create($appName);
            // $reporter = new Log($this->logger);
            $reporter = new Http(['endpoint_url' => $endpointUrl]);
            $sampler = BinarySampler::createAsAlwaysSample();
            self::$tracing = TracingBuilder::create()
                ->havingLocalEndpoint($endpoint)
                ->havingSampler($sampler)
                ->havingReporter($reporter)
                ->build();

            self::$tracer = self::$tracing->getTracer();
        }
    }

    private static function newChildSpan($spanName, $kind)
    {
        $childSpan = self::$tracer->newChild(self::$rootSpan->getContext());
        $childSpan->start();
        $childSpan->setKind($kind);
        $childSpan->setName($spanName);
        return $childSpan;
    }

    public static function getRpcSpan($request, &$headers = [])
    {
        if (self::$enabled) {
            $childSpan = self::newChildSpan($request->getMethod() . ' ' . $request->getUri(), 'CLIENT');

            $injector = self::$tracing->getPropagation()->getInjector(new Map());
            $injector($childSpan->getContext(), $headers);

            return $childSpan;
        }
         return false;
    }

    public static function getDbSpan($context, $sql = '')
    {
        if (self::$enabled) {
            return self::newChildSpan($sql ?: $context->sql, 'CLIENT');
        }
        return false;
    }
}